package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.itheima.pojo.PageBean;
import com.itheima.pojo.User;
import com.itheima.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private IUserService userService;

//    @Autowired
//    private UserMapper userMapper;

    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable  int currentPage,@PathVariable int pageSize) throws IOException {

        PageBean<User> bean = new PageBean<User>();
        IPage<User> page= new Page<>(currentPage,pageSize);
        userService.page(page,null);
        List<User> list = page.getRecords();
        long total = page.getTotal();
        bean.setRows(list);
        bean.setTotalCount(total);
        return new Result(Code.GET_OK,bean);
    }
    /**
     * 保存用户
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody  User user) {
        boolean b = userService.save(user);
        if (b) {
            return new Result(Code.SAVE_OK,null);
        }else {
            return new Result(Code.SAVE_ERR,null);
        }

    }

    /**
     * 根据用户id查询用户
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId,id);
        boolean b = userService.remove(wrapper);
        if (b) {
            return new Result(Code.DELETE_OK,null);
        }else {
            return new Result(Code.DELETE_ERR,null);
        }
    }

    /**
     * 更新用户
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        boolean b = userService.updateById(user);
        if (b) {
            return new Result(Code.DELETE_OK,null,"修改成功");
        }else {
            return new Result(Code.DELETE_ERR,null,"修改失败");
        }
    }


}
